package com.menglei.dailytasks.m0717;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.menglei.dailytasks.R;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class FileActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "MainActivity:TAG";
    private EditText mEtFileName;
    private EditText mEtInput;
    /**
     * 保存到内部文件中
     */
    private Button mBtnInSave;
    /**
     * 读取当前文件内容
     */
    private Button mBtnInRead;
    /**
     * 文件存储路径/内容
     */
    private TextView mTvInPrint;
    /**
     * 保存到外部文件中
     */
    private Button mBtnOutSave;
    /**
     * 读取当前文件内容
     */
    private Button mBtnOutRead;
    /**
     * 文件存储路径/内容
     */
    private TextView mTvOutPrint;
    /**
     * 保存到缓存文件中
     */
    private Button mBtnCacheSave;
    /**
     * 读取当前文件内容
     */
    private Button mBtnCacheRead;
    /**
     * 文件存储路径/内容
     */
    private TextView mTvCachePrint;
    /**
     * 保存 asset文件中
     */
    private Button mBtnAssetIn;
    /**
     * 读取当前文件内容
     */
    private Button mBtnAssetSave;
    /**
     * 文件存储路径/内容
     */
    private TextView mTvAssetPrint;
    /**
     * 保存到raw文件中
     */
    private Button mBtnRawSave;
    /**
     * 读取当前文件内容
     */
    private Button mBtnRawRead;
    /**
     * 文件存储路径/内容
     */
    private TextView mTvRawPrint;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file);
        initView();
        allExternalPath();
        //内部存储写入1

        try {
            FileInputStream in = getApplicationContext().openFileInput("test.txt");
            byte b[] = new byte[1024];
            int len = 0;
            ByteArrayOutputStream array = new ByteArrayOutputStream();
            while ((len = in.read(b)) != -1) { //开始读取文件
                array.write(b, 0, len);
            }
            byte data[] = array.toByteArray(); //把内存里的数据读取出来
            in.close();
            array.close();
            Log.i(TAG, new String(data));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //内部存储--cache
//        File file = new File(getCacheDir(),"cache.txt");
//        try {
//            FileOutputStream fos=new FileOutputStream(file);
//            fos.write("write to cache \n".getBytes());
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }

    private void initView() {
        mEtFileName = (EditText) findViewById(R.id.et_file_name);
        mEtInput = (EditText) findViewById(R.id.et_input);
        mBtnInSave = (Button) findViewById(R.id.btn_in_save);
        mBtnInSave.setOnClickListener(this);
        mBtnInRead = (Button) findViewById(R.id.btn_in_read);
        mBtnInRead.setOnClickListener(this);
        mTvInPrint = (TextView) findViewById(R.id.tv_in_print);
        mBtnOutSave = (Button) findViewById(R.id.btn_out_save);
        mBtnOutSave.setOnClickListener(this);
        mBtnOutRead = (Button) findViewById(R.id.btn_out_read);
        mBtnOutRead.setOnClickListener(this);
        mTvOutPrint = (TextView) findViewById(R.id.tv_out_print);
        mBtnAssetSave = (Button) findViewById(R.id.btn_asset_save);
        mBtnAssetSave.setOnClickListener(this);
        mTvAssetPrint = (TextView) findViewById(R.id.tv_asset_print);

        mBtnRawRead = (Button) findViewById(R.id.btn_raw_read);
        mBtnRawRead.setOnClickListener(this);
        mTvRawPrint = (TextView) findViewById(R.id.tv_raw_print);
    }

    private void writeToFile(String fileName, String content, int type) {
        File file = null;
        switch (type) {
            case 0://内部存储
                file = new File(getFilesDir(), fileName);
                break;
            case 1://
                file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), fileName);
                break;
            case 2://asset
                String str = "21231";
                str.replace("0","1");
                break;
        }
        try {
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(content.getBytes());
            fos.close();
            Toast.makeText(this, "存储成功", Toast.LENGTH_SHORT).show();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String readFile(String filename, int type) throws Exception {
        FileInputStream input;
        switch (type) {
            case 0:
                input = getApplicationContext().openFileInput(filename);
                break;
            case 1:
                input = new FileInputStream(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), filename));
                break;

            default:
                throw new IllegalStateException("Unexpected value: " + type);
        }
        byte b[] = new byte[1024];
        int len = 0;
        ByteArrayOutputStream array = new ByteArrayOutputStream();
        while ((len = input.read(b)) != -1) { //开始读取文件
            array.write(b, 0, len);
        }
        byte data[] = array.toByteArray(); //把内存里的数据读取出来
        input.close();
        array.close();
        return new String(data);
    }

    @Override
    public void onClick(View v) {
        if (TextUtils.isEmpty(mEtFileName.getText().toString())) {
            Toast.makeText(this, "文件名不能为空", Toast.LENGTH_SHORT).show();
        } else if (TextUtils.isEmpty(mEtInput.getText().toString())) {
            Toast.makeText(this, "输入不能为空", Toast.LENGTH_SHORT).show();
        } else {
            switch (v.getId()) {
                default:
                    break;
                case R.id.btn_in_save:
                    writeToFile(mEtFileName.getText().toString(), mEtInput.getText().toString(), 0);
                    break;
                case R.id.btn_in_read:
                    try {
                        mTvInPrint.setText(readFile(mEtFileName.getText().toString(), 0));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case R.id.btn_out_save:
                    requestPermission();
                    writeToFile(mEtFileName.getText().toString(), mEtInput.getText().toString(), 1);
                    break;
                case R.id.btn_out_read:
                    try {
                        mTvOutPrint.setText(readFile(mEtFileName.getText().toString(), 1));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case R.id.btn_asset_save:
                    InputStream in = null;
                    try {
                        in = getAssets().open("2.txt");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    byte b[] = new byte[1024];
                    int len = 0;
                    ByteArrayOutputStream array = new ByteArrayOutputStream();
                    while (true) {
                        try {
                            if (!((len = in.read(b)) != -1)) break;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        array.write(b, 0, len);
                    }
                    byte data[] = array.toByteArray();
                    try {
                        in.close();
                        array.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    mTvAssetPrint.setText(new String(data));
                    break;
                case R.id.btn_raw_read:
                    InputStream in1 = getResources().openRawResource(R.raw.text);
                    byte b1[] = new byte[1024];
                    int len1 = 0;
                    ByteArrayOutputStream array1 = new ByteArrayOutputStream();
                    while (true) {
                        try {
                            if (!((len1 = in1.read(b1)) != -1)) break;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        array1.write(b1, 0, len1);
                    }
                    byte data1[] = array1.toByteArray();
                    try {
                        in1.close();
                        array1.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    mTvRawPrint.setText(new String(data1));
                    break;
            }
        }

    }

    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            String[] permissions = {
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
            };
            for (String item : permissions) {
                if (checkSelfPermission(item) != PackageManager.PERMISSION_GRANTED) {
                    requestPermissions(permissions, 1);
                    return;
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1) {
            Toast.makeText(this, "请求权限成功", Toast.LENGTH_SHORT).show();
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    public void allExternalPath() {
        File[] files;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            files = getExternalFilesDirs(Environment.MEDIA_MOUNTED);
            for (File file : files) {
                Log.e("allExternalPath", file.toString());
            }
        }
    }

    public boolean isExternalStorageReadable() {
        String state = Environment.getExternalStorageState();
        Log.d("externalState", "state = " + state);
        if (Environment.MEDIA_MOUNTED.equals(state) ||
                Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            return true;
        }
        return false;
    }
}